package
{
	import org.osmf.elements.ParallelElement;
	import org.osmf.events.BufferEvent;
	import org.osmf.events.MediaElementEvent;
	import org.osmf.traits.BufferTrait;
	import org.osmf.traits.MediaTraitType;
	import org.osmf.traits.PlayState;
	import org.osmf.traits.PlayTrait;
	
	public class SynchronizedParallelElement extends ParallelElement
	{
		public function SynchronizedParallelElement()
		{
			addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
			addEventListener(MediaElementEvent.TRAIT_REMOVE, onTraitRemove);
			
			super();
		}
		
		// Internals
		//
		
		private var bufferable:BufferTrait;
		private var playable:PlayTrait;
		private var paused:Boolean;
		
		private function onTraitAdd(event:MediaElementEvent):void
		{
			switch (event.traitType)
			{
				case MediaTraitType.BUFFER:
					bufferable = BufferTrait(getTrait(event.traitType));
					bufferable.addEventListener(BufferEvent.BUFFER_TIME_CHANGE, updatePlayState);
					updatePlayState();
					break;
				
				case MediaTraitType.PLAY:
					playable = PlayTrait(getTrait(event.traitType));
					updatePlayState();
					break;
			}
		}
		
		private function onTraitRemove(event:MediaElementEvent):void
		{
			switch (event.traitType)
			{
				case MediaTraitType.BUFFER:
					bufferable.removeEventListener(BufferEvent.BUFFER_TIME_CHANGE, updatePlayState);
					bufferable = null;
					updatePlayState();
					break;
				
				case MediaTraitType.PLAY:
					playable = null;
					updatePlayState();
					break;
			}
		}
		
		private function updatePlayState(..._):void
		{
			if (playable && playable.canPause && bufferable)
			{
				if(paused == true
					&&playable.playState == PlayState.PAUSED
					&&bufferable.bufferTime >= bufferable.bufferLength)
				{
					paused = false;
					playable.play();
				}
				else if
					(    paused == false
						&&    playable.playState != PlayState.PAUSED
						&&     bufferable.bufferTime < bufferable.bufferLength
					)
				{
					paused = true;
					playable.pause();
				}
			}
		}
	}
	
}